package com.rui.sideup.test.socket;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


@Slf4j
public class ServerManager {

    private static final String TAG = "ServerManager";

    private static ServerManager serverManager;
    private ServerSocket serverSocket = null;

    private Map<WebSocket, String> clientMap = new HashMap<>();

    private ServerManager() {

    }

    public static synchronized ServerManager getInstance() {
        if (serverManager == null) {
            serverManager = new ServerManager();
        }
        return serverManager;
    }


    /**
     * 客户端连接
     *
     * @param clientName
     * @param socket
     */
    public void clientLogin(String clientName, WebSocket socket) {
        if (clientName != null || socket != null) {
            clientMap.put(socket, clientName);
            log.info("LOGIN:" + clientName);
            sendMessageToAll((clientName + "...Login...").getBytes());
        }
    }

    /**
     * 客户端断开
     *
     * @param socket
     */
    public void clientLeave(WebSocket socket) {
        if (clientMap.containsKey(socket)) {
            String clientName = clientMap.get(socket);
            log.info("Leave:" + clientName);
            clientMap.remove(socket);
            sendMessageToAll((clientName + "...Leave...").getBytes());
        }
    }

    public void sendMessageToUser(WebSocket socket, String message) {
        if (socket != null) {
            socket.send(message);
        }
    }

    /**
     * 发送给特定客户端
     *
     * @param clientName
     * @param message
     */
    public void sendMessageToUser(String clientName, String message) {
        Set<WebSocket> ketSet = clientMap.keySet();
        for (WebSocket socket : ketSet) {
            String name = clientMap.get(socket);
            if (name != null) {
                if (name.equals(clientName)) {
                    socket.send(message);
                    break;
                }
            }
        }
    }

    /**
     * 群发数据
     *
     * @param message
     */
    public void sendMessageToAll(byte[] message) {
        Set<WebSocket> ketSet = clientMap.keySet();

        log.info("在线client:{}", ketSet.size());

        for (WebSocket socket : ketSet) {
            String name = clientMap.get(socket);
            if (name != null) {
                socket.send(message);
                log.info("socket状态:{}", socket.isOpen());
                log.info("sendMessageToAll-conn地址:" + socket.toString());
            }
        }
    }

    /**
     * 开启websocket服务
     *
     * @param port
     * @return
     */
    public boolean start(int port) {

        if (port < 0) {
            log.info("Port error...");
            return false;
        }

        log.info("start ServerSocket...");

        try {
            serverSocket = new ServerSocket(this, port);
            serverSocket.start();
            log.info("start ServerSocket Success...");
            return true;
        } catch (Exception e) {
            log.info("start Failed...");
            // serverSocket.start();
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 停止服务
     *
     * @return
     */
    public boolean stop() {
        try {
            serverSocket.stop();
            log.info("stop ServerSocket Success...");
            return true;
        } catch (Exception e) {
            log.info("stop ServerSocket Failed...");
            e.printStackTrace();
            return false;
        }
    }
}